package com.ship.boats.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ship.boats.business.impl.BoatsSystemServiceImpl;
import com.ship.boats.domain.SpBoatsAisMessage;
import com.ship.boats.domain.dto.CreateBoatsAisMessageRq;
import com.ship.boats.domain.vo.*;
import com.ship.boats.mapper.SpBoatsAisMessageMapper;
import com.ship.boats.service.BoatsArchivesService;
import com.ship.boats.service.SpBoatsAisMessageService;
import com.ship.boats.service.SpBoatsSisterManageService;
import com.ship.common.core.constant.ShipApiConstants;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
     * <b>SpBoatsAisMessageServiceImpl</b>
 *
 * @description: SpBoatsAisMessageServiceImpl <br>
 * @date: 2024/4/3 11:03 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SpBoatsAisMessageServiceImpl extends ServiceImpl<SpBoatsAisMessageMapper, SpBoatsAisMessage> implements SpBoatsAisMessageService {
    private static final Logger logger = LoggerFactory.getLogger(SpBoatsAisMessageServiceImpl.class);

    @Autowired
    private BoatsArchivesService boatsArchivesService;

    @Autowired
    private SpBoatsSisterManageService spBoatsSisterManageService;

    @Autowired
    private BoatsSystemServiceImpl boatsSystemServiceImpl;


    @Override
//    @Scheduled(fixedRate = 120000) //每两分钟执行一次
    public void addBoatsAirMessage() {
        // 获取当前时间，根据需要可以自定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String tableSuffix = sdf.format(new Date());
        String tableName = "boats_ais_message" + tableSuffix;
        String status = baseMapper.queryTableName(tableName);
        if ("f".equals(status)){
            baseMapper.createTable(tableName);
        }
//        logger.info("开始查询ais信息时间:"+DateUtil.format(new Date(),DatePattern.NORM_DATETIME_FORMATTER));
        //查询所有的mmsi列表
        List<String> mmsiList = boatsArchivesService.queryMmsiList();
        if (CollectionUtil.isNotEmpty(mmsiList)){
            int number = 100;
            int count = mmsiList.size() / number;
            if (mmsiList.size() % number != 0){
                count++;
            }
            for (int i = 0; i < count; i++) {
                int formIndex = i*number;
                int toIndex = Math.min((i+1)*number,mmsiList.size());
                List<String> batchData = mmsiList.subList(formIndex,toIndex);
                if (CollectionUtil.isNotEmpty(batchData)){
                    String data = null;
                    for (int i1 = 0; i1 < batchData.size(); i1++) {
                        if (i1 == 0){
                            data = batchData.get(0);
                        }else {
                            data =data + ","+batchData.get(i1);
                        }
                    }
                    this.queryBoatsAirMessage(data,tableName);
                }
            }
        }
    }

    @Override
    public QueryBoatsAisMessageInfo queryAISMessageByImo(String imo) {
        QueryBoatsAisMessageInfo resultAisMessage = new QueryBoatsAisMessageInfo();
//        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
//        /* MINUTE 指示一天中的某分 */
//        calendar.set(Calendar.MINUTE,(calendar.get(Calendar.MINUTE) - 20));
//        String startDate = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MINUTE_FORMATTER);
//        String endDate = DateUtil.format(calendar.getTime(), DatePattern.NORM_DATETIME_MINUTE_FORMATTER);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String tableSuffix = sdf.format(new Date());
        String tableName = "boats_ais_message" + tableSuffix;
        List<SpBoatsAisMessage> boatsAisMessages = null;
        String status = baseMapper.queryTableName(tableName);
        if ("f".equals(status)){
            tableName = "boats_ais_message";
        }
        boatsAisMessages = baseMapper.queryAISMessageByImo(imo,tableName);
        if (CollectionUtil.isNotEmpty(boatsAisMessages)){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            SpBoatsAisMessage spBoatsAisMessage = boatsAisMessages.get(0);
            resultAisMessage.setShipId(spBoatsAisMessage.getShipId());
            resultAisMessage.setShipName(spBoatsAisMessage.getShipName());
            resultAisMessage.setMmsi(spBoatsAisMessage.getMmsi());
            resultAisMessage.setImo(spBoatsAisMessage.getImo());
            resultAisMessage.setCallsign(spBoatsAisMessage.getCallsign());
            resultAisMessage.setShiptype(spBoatsAisMessage.getShiptype());
            resultAisMessage.setLength(new BigDecimal(spBoatsAisMessage.getLength()));
            resultAisMessage.setBreadth(new BigDecimal(spBoatsAisMessage.getBreadth()));
            String eatTime = dateFormat.format(new Date(spBoatsAisMessage.getEta() * 1000L));
            resultAisMessage.setEta(eatTime);
            resultAisMessage.setDestPort(spBoatsAisMessage.getDestPort());
            resultAisMessage.setDraught(new BigDecimal(spBoatsAisMessage.getDraught()).divide(new BigDecimal(10)));
            String postTime = dateFormat.format(new Date(spBoatsAisMessage.getPosTime() * 1000L));
            resultAisMessage.setPosTime(postTime);
            resultAisMessage.setLon(new BigDecimal(spBoatsAisMessage.getLon()).divide(new BigDecimal(600000),4,BigDecimal.ROUND_UP));
            resultAisMessage.setLat(new BigDecimal(spBoatsAisMessage.getLat()).divide(new BigDecimal(600000),4,BigDecimal.ROUND_UP));
            resultAisMessage.setCog(new BigDecimal(spBoatsAisMessage.getCog()).divide(new BigDecimal(10)));
            resultAisMessage.setHeading(spBoatsAisMessage.getHeading());
            resultAisMessage.setSog(new BigDecimal(spBoatsAisMessage.getSog()).divide(new BigDecimal(10)));
            resultAisMessage.setRot(spBoatsAisMessage.getRot());
            resultAisMessage.setAisNavStatus(getAisNavStatus(spBoatsAisMessage.getAisNavStatus()));
            resultAisMessage.setEnable(spBoatsAisMessage.getEnable());
            resultAisMessage.setCreateTime(spBoatsAisMessage.getCreateTime());
            resultAisMessage.setUpdateTime(DateUtil.format(spBoatsAisMessage.getUpdateTime(),DatePattern.NORM_DATETIME_FORMATTER));
        }
        return resultAisMessage;
    }

    public String getAisNavStatus(String aisNavStatus){
        String resultStatus = null;
        switch (aisNavStatus){
            case "0":
                resultStatus = "在航";
                break;
            case "1":
                resultStatus = "锚泊";
                break;
            case "2":
                resultStatus = "未操纵";
                break;
            case "3":
                resultStatus = "有限适航性";
                break;
            case "4":
                resultStatus = "受船舶吃水限制";
                break;
            case "5":
                resultStatus = "系泊";
                break;
            case "6":
                resultStatus = "搁浅";
                break;
            case "7":
                resultStatus = "从事捕捞";
                break;
            case "8":
                resultStatus = "航行中";
                break;
        }
        return resultStatus;
    }


    @Override
    public List<BoatsPerformanceAnalysisInfo> queryBoatsPerformanceAnalysis(String imo, String startDate, String endDate) {
        String nowDate = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMATTER);
        startDate = startDate + " 00:00:00";
        if (startDate.equals(nowDate)){
            endDate = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER);
        }else {
            endDate = endDate +" 23:59:59";
        }
        List<BoatsPerformanceAnalysisInfo> list = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm");
        LocalDate startTime= LocalDate.parse(startDate, formatter);
        LocalDate endTime = LocalDate.parse(endDate, formatter);
        LocalDate currentDate = startTime;
        while (!currentDate.isAfter(endTime)) {
            ZonedDateTime zonedDateTime = currentDate.atStartOfDay(ZoneId.systemDefault());
            Date date = Date.from(zonedDateTime.toInstant());
            String format = DateUtil.format(date, DatePattern.PURE_DATE_FORMATTER);
            String tableName = "boats_ais_message" + format;
            String status = baseMapper.queryTableName(tableName);
            if ("t".equals(status)){
                List<BoatsPerformanceAnalysisInfo> boatsPerformanceList = baseMapper.queryBoatsPerformanceAnalysis(imo,startDate,endDate,tableName);
                if (CollectionUtil.isNotEmpty(boatsPerformanceList)){
                    list.addAll(boatsPerformanceList);
                }
            }
             currentDate = currentDate.plusDays(1);
        }

        return list;
    }

    @Override
    public List<QueryBoatsSisterInfo> queryBoatsSisterList(String imo) {
        List<String> imoList = spBoatsSisterManageService.queryBoatsSisterList(imo);
        List<String> imos = imoList.stream().distinct().collect(Collectors.toList());
        List<QueryBoatsSisterInfo> list = boatsArchivesService.queryBoatsSisterList(imos);
        return list;
    }

    @Override
    public String querySisterBoateName(String imo) {
        return spBoatsSisterManageService.querySisterBoateName(imo);
    }

    public void queryBoatsAirMessage(String data,String tableName){
        Map<String,String> map = new HashMap<>();
        map.put("mmsiList",data);
        Object messageData = boatsSystemServiceImpl.getBoatsUtil(map, ShipApiConstants.QUERY_BOATS_AIS_MESSAGE_URL);
        List<QueryAisStaticLatestInfo> aisStaticLatestList = JSONUtil.toList(JSONUtil.parseArray(messageData), QueryAisStaticLatestInfo.class);
//        logger.info("获取船舶AIS静态信息返回结果:{}"+JSONUtil.parse(aisStaticLatestList));
        if (CollectionUtil.isNotEmpty(aisStaticLatestList)){
            //查询船舶位
            Map<String,String> queryMap = new HashMap<>();
            String shipId = null;
            for (int i = 0; i < aisStaticLatestList.size(); i++) {
                if (i == 0){
                    shipId = aisStaticLatestList.get(0).getShipId();
                }else {
                    shipId =shipId + ","+aisStaticLatestList.get(i).getShipId();
                }
            }

            queryMap.put("shipId",shipId);
            Object obj = boatsSystemServiceImpl.getBoatsUtil(queryMap, ShipApiConstants.QUERY_BOATS_POSITION_LATEST_URL);
            List<QueryPositionLatestInfo> positionLatestList = JSONUtil.toList(JSONUtil.parseArray(obj), QueryPositionLatestInfo.class);
//            logger.info("获取ais信息返回结果:{}"+JSONUtil.parse(positionLatestList));
//            if (CollectionUtil.isNotEmpty(positionLatestList)){
//                Map<String, List<QueryPositionLatestInfo>> map1 = positionLatestList.stream().collect(Collectors.groupingBy(QueryPositionLatestInfo::getShipId));
//                aisStaticLatestList.forEach(item -> {
//                    CreateBoatsAisMessageRq spBoatsAisMessage = new CreateBoatsAisMessageRq();
//                    BeanUtils.copyProperties(item,spBoatsAisMessage);
//                    BeanUtils.copyProperties(map1.get(item.getShipId()).get(0),spBoatsAisMessage);
//                    spBoatsAisMessage.setEnable("1");
//                    spBoatsAisMessage.setCreateTime(new Date());
//                    spBoatsAisMessage.setUpdateTime(new Date());
//                    spBoatsAisMessage.setTableName(tableName);
//                    logger.info("保存AIS数据:{}"+JSONUtil.parse(spBoatsAisMessage));
//                    baseMapper.addBoatsAirMessage(spBoatsAisMessage);
//                });
//            }
            if (CollectionUtil.isNotEmpty(positionLatestList)) {
                Map<String, List<QueryPositionLatestInfo>> map1 = positionLatestList.stream()
                        .collect(Collectors.groupingBy(QueryPositionLatestInfo::getShipId));
                for (QueryAisStaticLatestInfo item : aisStaticLatestList) {
                    CreateBoatsAisMessageRq spBoatsAisMessage = new CreateBoatsAisMessageRq();
                    BeanUtils.copyProperties(item, spBoatsAisMessage);

                    List<QueryPositionLatestInfo> positionInfos = map1.get(item.getShipId());
                    if (CollectionUtil.isNotEmpty(positionInfos)) {
                        BeanUtils.copyProperties(positionInfos.get(0), spBoatsAisMessage);
                    } else {
                        // 记录日志或处理该情况（例如跳过或填充默认值）
                        logger.warn("未找到船舶ID {} 的最新位置信息", item.getShipId());
                        continue;
                    }

                    spBoatsAisMessage.setEnable("1");
                    spBoatsAisMessage.setCreateTime(new Date());
                    spBoatsAisMessage.setUpdateTime(new Date());
                    spBoatsAisMessage.setTableName(tableName);

                    baseMapper.addBoatsAirMessage(spBoatsAisMessage);
                }
            }

        }
    }
}
